/*
** env.c for 42sh in /home/guina_b/
** 
** Made by benoit guina
** Login   <guina_b@epitech.net>
** 
** Started on  Fri Jan 01 00:00:00 2010 benoit guina
** Last update Fri Jan 01 00:00:00 2010 benoit guina
*/

#include <string.h>
#include "alloc.h"
#include "env.h"

static unsigned int env_data_len(char **env_data)
{
  unsigned int i;

  i = -1;
  while (env_data[++i]);
  return (i);
}

char **env_copy_data(char **env_data, unsigned int *alloc_size)
{
  unsigned int i;
  char **r;

  if (*alloc_size < (i = env_data_len(env_data) + 1))
    *alloc_size = i;
  if ((r = xmalloc(*alloc_size * sizeof(char **), __FILE__, __LINE__)))
  {
    i = -1;
    while (env_data[++i])
      if ((r[i] = xmalloc(strlen(env_data[i]) + 1, __FILE__, __LINE__)))
        strcpy(r[i], env_data[i]);
      else
      {
        i = -1;
        while (r[++i])
          xfree(r[i]);
        xfree(r);
        return (0);
      }
    while (i < *alloc_size)
      r[i++] = 0;
  }
  return (r);
}

void env_free_data(char **env_data)
{
  int i;

  i = -1;
  while (env_data[++i])
    xfree(env_data[i]);
  xfree(env_data);
}

t_env *env_init(char **env_data, unsigned int alloc_size)
{
  t_env *r;

  if ((r = xmalloc(sizeof(t_env), __FILE__, __LINE__)))
  {
    r->len = -1;
    if ((r->data = env_copy_data(env_data, &alloc_size)))
    {
      r->len = env_data_len(r->data);
      r->alloc_size = alloc_size;
      return (r);
    }
    env_free(r);
  }
  return (0);
}

void env_free(t_env *env)
{
  env_free_data(env->data);
  xfree(env);
}
